/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.Map;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import org.apache.fop.apps.FOPException;
import org.apache.fop.apps.FOUserAgent;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;
import org.xml.sax.SAXException;

public class ReportUtils {

    public static ByteArrayOutputStream createFileFo(String webpath, String xslPath, String xmlPath, Map<String, Object> param, String output) throws FileNotFoundException, SAXException, IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            TransformerFactory tf = TransformerFactory.newInstance();
            StreamSource xslStream = new StreamSource(xslPath);
            Transformer trans = tf.newTransformer(xslStream);
            StreamSource xmlStream = new StreamSource(xmlPath);
            StreamResult rs = new StreamResult(new FileOutputStream(output));
            Set<String> keys = param.keySet();
            for (String key : keys) {
                trans.setParameter(key, param.get(key));
            }
            trans.transform(xmlStream, rs);

            FopFactory foFactory = FopFactory.newInstance();
            Fop fop = foFactory.newFop(MimeConstants.MIME_PDF, out);
            File config = new File(webpath + "WEB-INF/Report/myconfig.xconf");
            foFactory.setUserConfig(config);
            
            TransformerFactory tfac = TransformerFactory.newInstance();
            Transformer transformer = tfac.newTransformer();

            //parse string to domsource, string is .fo content generated
            Source src = new StreamSource(new File(output));

            Result res = new SAXResult(fop.getDefaultHandler());
            transformer.transform(src, res);
            out.close();
            return out;

        } catch (TransformerConfigurationException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        } catch (TransformerException ex) {
            Logger.getLogger(XmlUtils.class.getName()).log(Level.SEVERE, null, ex);
        }
        return out;
    }
}
